package com.usian.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.usian.common.wemedia.WemediaContans;
import com.usian.model.base.BaseServiceImpl;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.media.dtos.WmNewsDto;
import com.usian.model.media.dtos.WmNewsPageReqDto;
import com.usian.model.media.pojos.WmMaterial;
import com.usian.model.media.pojos.WmNews;
import com.usian.utils.threadlocal.ThreadLocalUtils;
import com.usian.wemedia.mapper.WmMaterialMapper;
import com.usian.wemedia.mapper.WmNewsMapper;
import com.usian.wemedia.mapper.WmNewsMaterialMapper;
import com.usian.wemedia.service.WmNewsService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class WmNewsServiceImpl extends BaseServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Value("${fdfs.url}")
    private String baseUrl;
    @Autowired
    private WmMaterialMapper wmMaterialMapper;
    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Override
    public ResponseResult findAll(WmNewsPageReqDto dto) {
        if (dto == null) return errorParam;
        LambdaQueryWrapper<WmNews> wrapper = new LambdaQueryWrapper<>();
        //状态的判断，可以传过去，也可以不传
        wrapper.eq(dto.getStatus() != null, WmNews::getStatus, dto.getStatus());
        //频道的判断，可以传过去，也可以不传
        wrapper.eq(dto.getChannelId() != null, WmNews::getChannelId, dto.getChannelId());
        //对标题的模糊查询,可以传过去，也可以不传
        wrapper.like(dto.getKeyword() != null, WmNews::getTitle, dto.getKeyword());
        //如果第一页的展示没有时间
        if (dto.getMaxTime() == null) dto.setMaxTime(new Date());
        wrapper.lt(WmNews::getPublishTime, dto.getMaxTime());
        //排序方式
        wrapper.orderByDesc(WmNews::getPublishTime);
        //只能查询自己的数据通过登录的id
        wrapper.eq(WmNews::getUserId, ThreadLocalUtils.getUserId());
        return getPageData(dto, wrapper);
    }

    @Override
    public ResponseResult saveNews(WmNewsDto wmNews, Short isSubmit) {
        if (wmNews == null) return errorParam;
        WmNews news = new WmNews();
        //把wmNews的值复制到新对象中
        BeanUtils.copyProperties(wmNews, news);
        //判断传过来的id为空则是保存数据，反之修改数据
        if (wmNews.getId() == null) {
            save(news);
            //返回一个id
            Integer newsId = news.getId();
            //定义一个集合存储传过来的素材
            ArrayList<String> imageList = new ArrayList<>();
            String content = wmNews.getContent();
            JSONArray objects = JSON.parseArray(content);
            objects.forEach(o -> {
                JSONObject object = JSONObject.parseObject(o.toString());
                if (object.getString("type").equals("image")) {
                    String image = object.getString("value");
                    imageList.add(image.replace(baseUrl, ""));
                }
            });
            //通过 登录id、素材集合 来进行查询数据
            LambdaQueryWrapper<WmMaterial> materiaWrapper = new LambdaQueryWrapper<>();
            materiaWrapper.eq(WmMaterial::getUserId, ThreadLocalUtils.getUserId());
            materiaWrapper.in(WmMaterial::getUrl, imageList);
            List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(materiaWrapper);
            //之后赋值到另一个集合中
            List<String> ids = wmMaterials.stream().map(m -> m.getId()+"").collect(Collectors.toList());
            wmNewsMaterialMapper.saveRelationsByContent(ids,newsId, WemediaContans.WM_CONTENT_REFERENCE);
            //以上为素材与新闻表的关系处理
        } else {
            updateById(news);
        }
        return null;
    }
}
